<?php
//error_reporting(0);
date_default_timezone_set("UTC");
include_once("CommonFeatures.php");
include_once("ReadNotifications.php");
class ReadFeedAction extends PostAction{
    
    //public $postAction;
    private $loggedInUserId=0;
    public $pdodbobj;
    public $connstatus=false;
    public $eLog;
    function __construct() {
          $this->eLog= new Log();
          
       try{
            
            $this->pdodbobj= new DB();
            $this->connstatus=$this->pdodbobj->connect();
            
            if(isset($_SESSION['Allyfolio_User_ID'])&& !empty($_SESSION['Allyfolio_User_ID']) && is_numeric($_SESSION['Allyfolio_User_ID'])){
                $this->loggedInUserId=trim($_SESSION['Allyfolio_User_ID']);    
            }
            else{
                $this->eLog->writeVerbose('ReadFeedAction:__construct():: Invalid Session => '.$_SESSION['Allyfolio_User_ID'].' \t');
                die('ReadFeedAction:__construct():: Invalid Session => '.$_SESSION['Allyfolio_User_ID'].' \t'. "\n");
            }
        }
        catch(Exception $ex){
            $this->eLog->writeException('ReadFeedAction:__construct():: \t'. $ex->getMessage(). "\n");
            die('ReadFeedAction:__construct():: \t'. $ex->getMessage(). "\n");   
        }
   }
        
    //check if user is authorised by comparining passed userid with session id
    public function isAuthenticated($userId){
        //global $loggedInUserId;
        if(isset($userId) && !empty($userId)  && is_numeric($userId) && $this->loggedInUserId==$userId){
            $this->eLog->writeVerbose('User: '.$userId.' is auhenticated \t');
            return true;
        }
        else{
            $this->eLog->writeVerbose('User: '.$userId.' is Not authenticated \t');
            return false;
        }
    }
    
    public function ReadCommentUploads($postId,$commentID){
        $postAction= new PostAction();
        $actionRes = $postAction->Failure;
        $postStatusTypes= new PostStatus();
        try{
            $this->eLog->writeVerbose('ReadFeedAction:ReadCommentUploads():: Starts \t');
            //do your stuff
            if($this->loggedInUserId!=null && is_numeric($this->loggedInUserId) && $this->loggedInUserId>0){                
                if($this->pdodbobj!=null){
                    $selquery="select * from af_user_posts_comments_media_uploads where Comment_ID=:cid and Status=:statusid";
                    $feedCommentsRecords= $this->pdodbobj->fetch_array(
                                        $this->pdodbobj->query($selquery,
                                                                 array(
                                                                 ":cid"=>$commentID,
                                                                 ":statusid"=>$postStatusTypes->Visible
                                                                 )
                                                               ));
                //$postStatusTypes->reportAbuse->Remove_Media_I_Dont_Like_This
        
                    return $feedCommentsRecords;
                }
                else{
                    $actionRes=$postAction->Failure;
                    $actionRes["msg"]="Unable to connect to db";
                    $this->eLog->writeVerbose('ReadFeedAction:ReadCommentUploads():: Message => '.$actionRes["msg"].' \t');
                }
            }
            else{
                $actionRes=$postAction->Failed_For_Invalid_Session;
                $this->eLog->writeVerbose('ReadFeedAction:ReadCommentUploads():: Message => '.$actionRes["msg"].' \t');
                //die('PerformPostAction:PostData():: Invalid UserId \t'."\n");
            }
            $this->eLog->writeVerbose('ReadFeedAction:ReadCommentUploads():: Ends \t');
        }
        catch(Exception $ex){
            $actionRes['msg']=$ex->getMessage();
            $this->eLog->writeException('ReadFeedAction:ReadCommentUploads():: Exception => '.$actionRes["msg"].' \t');
            die('ReadNewsFeed:ReadCommentUploads():: \t'. $ex->getMessage(). "\n");   
        }
        return $actionRes;
    }
    
    public function ReadPostComments($postId){
        $postAction= new PostAction();
        $actionRes = $postAction->Failure;
        $postStatusTypes= new PostStatus();
        try{
            $this->eLog->writeVerbose('ReadFeedAction:ReadPostComments():: Starts \t');
            //do your stuff
            if($this->loggedInUserId!=null && is_numeric($this->loggedInUserId) && $this->loggedInUserId>0){                
                if($this->pdodbobj!=null){
                    $selquery="SELECT upc . * ,u.Full_Name,u.Last_Name,u.Gender,u.Profile_Pic_Path,u.Login_Status,u.Is_Celebrity,u.Profile_Status
                                FROM af_user_posts_comments AS upc, af_users AS u
                                WHERE upc.Post_ID =:postid
                                AND upc.Status =:statusid
                                AND upc.User_ID = u.User_ID";
//                    $selquery="select * from af_user_posts_comments where Post_ID=:postid and Status=:statusid";
                    $feedCommentsRecords= $this->pdodbobj->fetch_array(
                                        $this->pdodbobj->query($selquery,
                                                                 array(
                                                                 ":postid"=>$postId,
                                                                 ":statusid"=>$postStatusTypes->Visible
                                                                 )
                                                               ));
                //$postStatusTypes->reportAbuse->Remove_Media_I_Dont_Like_This
        
                    return $feedCommentsRecords;
                }
                else{
                    $actionRes=$postAction->Failure;
                    $actionRes["msg"]="Unable to connect to db";
                    $this->eLog->writeVerbose('ReadFeedAction:ReadPostComments():: Message => '.$actionRes["msg"].' \t');
                }
            }
            else{
                $actionRes=$postAction->Failed_For_Invalid_Session;
                $this->eLog->writeVerbose('ReadFeedAction:ReadPostComments():: Message => '.$actionRes["msg"].' \t');
                //die('PerformPostAction:PostData():: Invalid UserId \t'."\n");
            }
            $this->eLog->writeVerbose('ReadFeedAction:ReadPostComments():: Ends \t');
        }
        catch(Exception $ex){
            $actionRes['msg']=$ex->getMessage();
            $this->eLog->writeException('ReadFeedAction:ReadPostComments():: Exception => '.$ex->getMessage().' \t');
            die('ReadNewsFeed:ReadPostComments():: \t'. $ex->getMessage(). "\n");   
        }
        return $actionRes;
    }
    
    public function ReadPostUploads($postId){
        $postAction= new PostAction();
        $actionRes = $postAction->Failure;
        $postStatusTypes= new PostStatus();
        try{
            $this->eLog->writeVerbose('ReadFeedAction:ReadPostUploads():: Starts \t');
            //do your stuff
            if($this->loggedInUserId!=null && is_numeric($this->loggedInUserId) && $this->loggedInUserId>0){                
                if($this->pdodbobj!=null){
                    $selquery="select * from af_user_posts_media_uploads where Post_ID=:postid and Status=:statusid";
                    $feedCommentsRecords= $this->pdodbobj->fetch_array(
                                        $this->pdodbobj->query($selquery,
                                                                 array(
                                                                 ":postid"=>$postId,
                                                                 ":statusid"=>$postStatusTypes->Visible
                                                                 )
                                                               ));
                //$postStatusTypes->reportAbuse->Remove_Media_I_Dont_Like_This
        
                    return $feedCommentsRecords;
                }
                else{
                    $actionRes=$postAction->Failure;
                    $actionRes["msg"]="Unable to connect to db";
                    $this->eLog->writeVerbose('ReadFeedAction:ReadPostUploads():: Message => '.$actionRes["msg"].' \t');
                }
            }
            else{
                $actionRes=$postAction->Failed_For_Invalid_Session;
                $this->eLog->writeVerbose('ReadFeedAction:ReadPostUploads():: Message => '.$actionRes["msg"].' \t');
                //die('PerformPostAction:PostData():: Invalid UserId \t'."\n");
            }
            $this->eLog->writeVerbose('ReadFeedAction:ReadPostUploads():: Ends \t');
        }
        catch(Exception $ex){
            $actionRes['msg']=$ex->getMessage();
            $this->eLog->writeException('ReadFeedAction:ReadPostUploads():: Exception => '.$actionRes["msg"].' \t');
            die('ReadNewsFeed:ReadPostUploads():: \t'. $ex->getMessage(). "\n");   
        }
        return $actionRes;
    }                    
    
    /**
     PostData : used to post any data with privacy setting, userid, and enumerated post type
     
     Result: PostAction::Contants (default: PostAction::Failure ==> 200)
     * 
     */
    public function ReadStatusUpdates($userId,$privacyType=PrivacySettings::DefaultSetting,$lastfeedid=0,$limitlen=10,$whichPostsToRead,$parentid=0,$clusteredId=0,$strSearch=""){
        //echo ("Parameters: postcontent:".$postcontent."\t Userid:".$userId."\t postType:".$postType."\t privacyType: ".$privacyType);
        //echo $strSearch;
        $postAction= new PostAction();
        $actionRes = $postAction->Failure;
        try{
            $this->eLog->writeVerbose('ReadFeedAction:ReadStatusUpdates():: Starts \t');
            //echo "<br>-->  doing stuff-->";
            //do your stuff
            if(ReadFeedAction::isAuthenticated($userId)){
                
                if($this->pdodbobj!=null){// check if connection object is set to connection
                    //read own posts 
                    //read posts from friends based on privacy setting: public or friends  
                    //read posts from from cluster or groups
                    //,count(upc.User_Comment_ID)as CommentsCount,count(upc.Media_Upload_ID)as MediaCount,
                    /*
    
                        Left Join
                        (
                            af_user_posts_comments as upc
                            on
                            upa.POST_ID=upc.POST_ID
                        )
                        
                        Left Join
                        (
                            af_user_posts_media_uploads as upmu
                            on
                            upa.POST_ID=upmu.POST_ID
                        )
                    */
                         
                    $readMostTrendingPosts=false;
                    $conditionArray=array();
                    
                    if(trim($whichPostsToRead)==7){
                        $selquery="SELECT NW.ID AS WatcherID, NW.Source_User_ID, NW.Target_User_ID, NW.Unique_NameToLink, 
                            NW.Notification_Date, NW.Status, AF.*                            
                            FROM af_notificationwatcher AS NW, af_user_posts_activities AS AF
                            WHERE NW.Unique_ID = AF.Post_ID
                            AND NW.ActivityFor =  'Techno' 
                            and NW.ID
                            ";
                        
                        if($parentid!=-2){
                            $selquery.=" and (NW.Target_User_ID=".$userId." || NW.Source_User_ID=".$userId.")";
                        }
                        if(strlen($strSearch)>0){
                            $selquery.=" and AF.Post_Title like '%".$strSearch."%'";
                        }
                        if($parentid==-2){
                            //means read most trending posts for techno-network
                            $readMostTrendingPosts=true;
                        }
                        else if($parentid>0){
                            //means we are fetching techno posts based on category
                            // need to show: Mine Post / Liked Post / Followed Post / Shared Post / Tagged Post
                            //$selquery.=" and AF.User_ID=:userid ";                            
                            //$conditionArray[":userid"]=$userId;
                            
                        } 
                        $conditionArray[":last_tracked_id"]=abs($lastfeedid);
                            
                    }
                    else{
                        $conditionArray= array(
                         ":userid"=>$userId,
                         ":publicSetting"=>PrivacySettings::PublicSetting,
                         ":friendsSetting"=>PrivacySettings::FriendsSetting,
                         ":last_tracked_id"=>abs($lastfeedid)
                         );
                         
                         $selquery=" 
                            select *
                                from 
                                    af_user_posts_activities as upa
                                    where 
                                        upa.POST_ID in (
                                            select POST_ID 
                                                from 
                                                    af_user_posts_activities 
                                                where 
                                                    User_ID=:userid 
                                                    
                                            Union
                                            (
                                                /* read posts from friends based on privacy setting: public or friends  */
                                                select POST_ID 
                                                    from 
                                                        af_user_posts_activities as uPosts
                                                    where 
                                                        uPosts.User_ID in(    
                                                            select User_Friend_ID 
                                                                from 
                                                                    af_user_friends as uFriends,
                                                                    af_user_privacy_settings as fPrivacySettings
                                                                where
                                                                    uFriends.User_ID=:userid
                                                                    and
                                                                    fPrivacySettings.User_ID=uFriends.User_Friend_ID
                                                        )
                                                        and uPosts.Privacy_Type_ID in(:publicSetting,:friendsSetting)
                                            )
                                        )
                                        and  upa.Post_Type_ID<>7                                                                                                                                                              
                                        
                              ";
                         }     
                              if(trim($whichPostsToRead)==7 /* techno */ || trim($whichPostsToRead)==6 /* blog */){
                                $selquery.=" and Post_Type_ID=".$whichPostsToRead;
                              }
                              
                              //." and Parent_ID=".$parentid
                              if($parentid!="" && is_numeric($parentid) && $parentid>0){
                                $selquery.=" and Parent_ID=".$parentid;
                              }
                              
                              //trending posts
                              if(trim($whichPostsToRead)==7){
                                  if($lastfeedid>=0){
                                    $selquery.=" and NW.ID>:last_tracked_id";
                                  }
                                  else{
                                    $selquery.=" and NW.ID<:last_tracked_id";                                        
                                  }
                                  
                                  if($readMostTrendingPosts){
                                    $selquery.=" group  by AF.Post_ID order by AF.Total_Shares desc,AF.Total_Likes desc";
                                  }
                                  else{
                                    $selquery.=" group  by AF.Post_ID order by NW.ID desc";
                                  }
                              }
                              else{
                                if($lastfeedid>=0){
                                    $selquery.=" and Post_ID>:last_tracked_id";
                                  }
                                  else{
                                    $selquery.=" and Post_ID<:last_tracked_id";                                        
                                  }
                                $selquery.=" order by Post_ID desc";
                              }
                              $selquery.=" limit ".$limitlen." ";
                              
                              //echo $selquery;
                              //print_r($conditionArray);
                              //die("====");
//                              echo "\n userid: ".$userId;
//                              echo "\n public setting: ".PrivacySettings::PublicSetting;
//                              echo "\n friendssettings: ".PrivacySettings::FriendsSetting;
//                              echo "\n last_post_id".$lastfeedid;
                              
                    $feedRecords= $this->pdodbobj->fetch_array($this->pdodbobj->query($selquery,$conditionArray));
                    
                    
                    return $feedRecords;
                }
                else{
                    $actionRes=$postAction->Failure;
                    $actionRes["msg"]="Unable to connect to db";
                    $this->eLog->writeVerbose('ReadFeedAction:ReadStatusUpdates():: Message => '.$actionRes["msg"].' \t');
                }
//                $actionRes=$postAction->Success;
            }
            else{
                $actionRes=$postAction->Failed_For_Invalid_Session;
                $this->eLog->writeVerbose('ReadFeedAction:ReadStatusUpdates():: Message => '.$actionRes["msg"].' \t');
                //die('PerformPostAction:PostData():: Invalid UserId \t'."\n");
            }
            $this->eLog->writeVerbose('ReadFeedAction:ReadStatusUpdates():: Ends \t');
        }
        catch(Exception $ex){
            $actionRes['msg']=$ex->getMessage();
            $this->eLog->writeException('ReadFeedAction:ReadStatusUpdates():: Exception => '.$actionRes["msg"].' \t');
            die('ReadNewsFeed:ReadStatusUpdates():: \t'. $ex->getMessage(). "\n");   
        }
        return $actionRes;
    }
    
    public function getPostLikesCount($postId){
        //echo ("Parameters: postcontent:".$postcontent."\t Userid:".$userId."\t postType:".$postType."\t privacyType: ".$privacyType);
        $oNotification=new Notifications();
        $totalRowsCount=$oNotification->getFeedLikeCommentShareCount($postId,"like");
        /*
        $postAction= new PostAction();
        $totalRowsCount=0;
        try{
            if($this->pdodbobj!=null){// check if connection object is set to connection
                $selquery=" select * from af_user_post_likes where POST_ID=:postid";                              
                $totalRowsCount=$this->pdodbobj->fetch_num_of_rows($this->pdodbobj->query($selquery,array(":postid"=>$postId)));
            }
        }
        catch(Exception $ex){
            $this->eLog->writeException('ReadFeedAction:getPostLikesCount():: Exception => '.$actionRes["msg"].' \t');
        }*/
        return $totalRowsCount;
    }
    public function getCommentLikesCount($feedid,$commentId){
        $oNotification=new Notifications();
        $totalRowsCount=$oNotification->getFeedLikeCommentShareCount($feedid,"commentlike",$commentId);
        return $totalRowsCount;
    }
    public function getPostShareCount($postId){
        //echo ("Parameters: postcontent:".$postcontent."\t Userid:".$userId."\t postType:".$postType."\t privacyType: ".$privacyType);
        $oNotification=new Notifications();
        $totalRowsCount=$oNotification->getFeedLikeCommentShareCount($postId,"share");
        return $totalRowsCount;
    }
    public function getPostCommentCount($postId){
        //echo ("Parameters: postcontent:".$postcontent."\t Userid:".$userId."\t postType:".$postType."\t privacyType: ".$privacyType);
        $oNotification=new Notifications();
        $totalRowsCount=$oNotification->getFeedLikeCommentShareCount($postId,"comment");
        return $totalRowsCount;
    }
    public function getPostSnapshotDetails($postId,$whichPostsToRead,$parentid=0,$clusteredId=0){
        //echo ("Parameters: postcontent:".$postcontent."\t Userid:".$userId."\t postType:".$postType."\t privacyType: ".$privacyType);
        $postAction= new PostAction();
        $actionRes = $postAction->Failure;
        try{
            $this->eLog->writeVerbose('ReadFeedAction:getPostSnapshotDetails():: Starts \t');
            //echo "<br>-->  doing stuff-->";
            //do your stuff
            if(ReadFeedAction::isAuthenticated($this->loggedInUserId)){
                
                if($this->pdodbobj!=null){// check if connection object is set to connection
                    $selquery=" select 
                                    upa.*,u.Full_Name,u.Last_Name,u.Gender,u.Profile_Pic_Path,u.Login_Status,u.Is_Celebrity,u.Profile_Status
                                from 
                                    af_user_posts_activities as upa,
                                    af_users as u
                                where 
                                    upa.POST_ID=:postid
                                    and 
                                    upa.User_ID=u.User_ID
                                    ";
                              
                              if(trim($whichPostsToRead)==7 /* techno */ || trim($whichPostsToRead)==6 /* blog */){
                                $selquery.=" and Post_Type_ID=".$whichPostsToRead;
                              }
                              
                              //." and Parent_ID=".$parentid
                              if($parentid!="" && is_numeric($parentid) && $parentid>0){
                                $selquery.=" and Parent_ID=".$parentid;
                              }
                    $feedRecords= $this->pdodbobj->fetch_array($this->pdodbobj->query($selquery,array(":postid"=>$postId)));
                    
                    
                    return $feedRecords;
                }
                else{
                    $actionRes=$postAction->Failure;
                    $actionRes["msg"]="Unable to connect to db";
                    $this->eLog->writeVerbose('ReadFeedAction:getPostSnapshotDetails():: Message => '.$actionRes["msg"].' \t');
                }
//                $actionRes=$postAction->Success;
            }
            else{
                $actionRes=$postAction->Failed_For_Invalid_Session;
                $this->eLog->writeVerbose('ReadFeedAction:getPostSnapshotDetails():: Message => '.$actionRes["msg"].' \t');
                //die('PerformPostAction:PostData():: Invalid UserId \t'."\n");
            }
            $this->eLog->writeVerbose('ReadFeedAction:getPostSnapshotDetails():: Ends \t');
        }
        catch(Exception $ex){
            $actionRes['msg']=$ex->getMessage();
            $this->eLog->writeException('ReadFeedAction:getPostSnapshotDetails():: Exception => '.$actionRes["msg"].' \t');
            die('ReadNewsFeed:getPostSnapshotDetails():: \t'. $ex->getMessage(). "\n");   
        }
        return $actionRes;
    }
}

?>